/**
 *                            License
 * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS  
 * CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). 
 * THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW.  
 * ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR  
 * COPYRIGHT LAW IS PROHIBITED.
 * 
 * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND  
 * AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE  
 * MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED 
 * HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.
 * 
 */
package l1j.server.server.datatables;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.L1DatabaseFactory;
import l1j.server.server.model.quest.L1QuestTemp;
import l1j.server.server.utils.BasicCheck;
import l1j.server.server.utils.SQLUtil;
import l1j.server.server.utils.collections.Maps;

public class QuestTable {
	private static Logger _log = Logger.getLogger(QuestTable.class.getName());
	
	private static QuestTable _instance;
	
	private static final Map<Integer, L1QuestTemp> _allQuest = Maps.newMap(); // 所有任務
	
	public static QuestTable getInstance() {
		if (_instance == null) {
			_instance = new QuestTable();
		}
		return _instance;
	}
	
	public QuestTable() {
		loadQuest();
	}
	
	public L1QuestTemp getTemplate(int _qid) {
		return getTemplate(_qid, 1);
	}
	
	public L1QuestTemp getTemplate(int _qid, int _qstep) {
		L1QuestTemp temp = _allQuest.get(_qid);
		if (temp != null && temp.getStep() == _qstep) {
			return temp;
		}
		return null;
	}
	/**
	 * 讀取所有的任務
	 */
	private void loadQuest() {
		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		L1QuestTemp quest;
		try {
			con = L1DatabaseFactory.getInstance().getConnection();
			pstm = con.prepareStatement("select * from quest");
			rs = pstm.executeQuery();
			
			while (rs.next()) {
				quest = new L1QuestTemp();
				quest.setId(rs.getInt("id"));
				quest.setStep(rs.getInt("step"));
				quest.setName(rs.getString("name"));
				//quest.setRepeat(rs.getBoolean("repeat"));
				quest.setMob(BasicCheck.getIArrFromS(rs.getString("mob")));
				quest.setMobName(BasicCheck.getSArrFromS(rs.getString("mob_name")));
				quest.setMobTotal(BasicCheck.getIArrFromS(rs.getString("mob_total")));

				_allQuest.put(quest.getId(), quest);
			}
		} catch (SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs, pstm, con);
		}
	}
}